package com.leyou.page.service;

import com.leyou.client.item.ItemClient;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SputDTO;
import com.leyou.item.pojo.Brand;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 详情业务
 */
@Service
public class PageService {
    @Autowired
    private ItemClient itemClient;
    @Value("${ly.static.itemDir}")
    private String itemDir;//静态页面保存路径
    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;//模板文件的名称
    @Autowired
    private SpringTemplateEngine templateEngine;//模板引擎对象


    public Map<String,Object> getPageDetail(Long id) {
        Map<String,Object> resultMap = new HashMap<>();

        //1.根据spuId查询SpuDTO
        SputDTO sputDTO = itemClient.findSpuById(id);
        //2.根据分类ID集合 获取 分类对象集合
        List<Category> categories = itemClient.findCategoriesByIds(
                Arrays.asList(sputDTO.getCid1(), sputDTO.getCid2(), sputDTO.getCid3())
        );
        //3.根据分类ID查询规格组（包含组内参数）
        List<SpecGroupDTO> specGroupDTOList = itemClient.findSpecGroupParamsByCid(sputDTO.getCid3());
        //4.根据品牌ID查询品牌对象
        Brand brand = itemClient.findBrandById(sputDTO.getBrandId());

        resultMap.put("categories",categories);
        resultMap.put("brand",brand);
        resultMap.put("spuName",sputDTO.getName());
        resultMap.put("subTitle",sputDTO.getSubTitle());
        resultMap.put("detail",sputDTO.getSpuDetail());
        resultMap.put("skus",sputDTO.getSkus());
        resultMap.put("specs",specGroupDTOList);
        return resultMap;
    }

    /**
     * 生成商品详情的静态页面
     */
    public void createStaticPage(Long spuId){
        //1.创建Context对象
        Context context = new Context();
        //设置动态数据
        context.setVariables(this.getPageDetail(spuId));

        //2.准备模板文件（Thymeleaf自动到templates默认路径查询指定的文件）
        String templateName = itemTemplate+".html";

        //3.利用模板引擎写出静态页面
        /**
         * 参数一：模板文件
         * 参数二：Context上下文对象
         */
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new File(itemDir,spuId+".html"));
            templateEngine.process(templateName,context,writer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.DATA_TRANSFER_ERROR);
        }finally {
            //注意: 必须把输出流关闭，否则后续无法删除该文件
            writer.close();
        }

    }


    public void deleteStaticPage(Long spuId) {
        try {
            //1.读取到商品详情静态页文件
            String fileName = spuId+".html";

            File file = new File( itemDir , fileName);

            //2.删除文件
            if(file.exists()){
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }
}
